package utils

import (
	"errors"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

/*PathExists
判断文件或文件夹是否存在:
如果返回的错误为nil,说明文件或文件夹存在
如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
如果返回的错误为其它类型,则不确定是否在存在
*/
func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

//ToString 所有类型转sring
func ToString(data interface{}) string {
	var res string = ""
	switch data.(type) {
	case string:
		res = data.(string)
		break
	case int:
		res = strconv.Itoa(data.(int))
		break
	case int64:
		res = strconv.FormatInt(data.(int64), 10)
		break
	case float32:
		res = strconv.FormatFloat(data.(float64), 'f', -1, 32)
		break
	case float64:
		res = strconv.FormatFloat(data.(float64), 'f', -1, 64)
		break
	case bool:
		res = strconv.FormatBool(data.(bool))
		break
	}
	return res
}

//CopyFile 复制文件，dstName要复制到的地方。srcName要复制的文件
func CopyFile(dstName, srcName string) (written int64, err error) {
	dstDir := filepath.Dir(dstName)
	if !PathExists(dstDir) {
		err = os.MkdirAll(dstDir, 0666)
		if err != nil {
			return 0, errors.New("创建目录失败，" + err.Error())
		}
	}
	src, err := os.Open(srcName)
	if err != nil {
		return 0, errors.New("打开文件失败," + err.Error())
	}
	defer func() {_=src.Close()}()

	dst, err := os.Create(dstName)
	if err != nil {
		return 0, errors.New("创建文件失败," + err.Error())
	}
	defer func() {_=dst.Close()}()

	return io.Copy(dst, src)
}

//RouteToAuthCode 路由转权限标识
func RouteToAuthCode(router string, method string) string {
	authCode := router
	authCode = strings.ReplaceAll(authCode, ":page_size/:page", "paginate")
	authCode = strings.ReplaceAll(authCode, "/:", "_")
	authCode = strings.ReplaceAll(authCode, "/", "_")
	authCode = strings.ReplaceAll(authCode, ":", "_")
	authCode = strings.ReplaceAll(authCode, "-", "_")
	authCode += "_" + strings.ToLower(method)
	return authCode
}
